<?php

namespace Wap\Action;

use Think\Controller;

class BaseAction extends Controller {

    public function __construct() {
        parent::__construct();

        $user = unserialize(cookie('MX_USER'));
        if (!empty($user) && $user['userId'] > 0 && $user['userPhone'] != '') {
            $this->assign('user_login', 1);
        } else {
            $this->assign('user_login', 0);
        }
    }

    public function restApi($code, $info = '', $data = array()) {
        if (empty($data) || !is_array($data)) {
            exit(json_encode(array('code' => $code, 'info' => $info)));
        }
        exit(json_encode(array('code' => $code, 'info' => $info, 'data' => $data)));
    }

    public function isUserLogin() {
        $rt = array();
        $rt['code'] = 100001;
        $rt['info'] = '请登录!';

        $user = unserialize(cookie('MX_USER'));
        if (!empty($user) && $user['userId'] > 0 && $user['userPhone'] != '') {
            return $user;
        }

        $this->restApi($rt['code'], $rt['info']);
    }

    public function checkLogin() {
        $user = unserialize(cookie('MX_USER'));
        if (!empty($user) && $user['userId'] > 0 && $user['userPhone'] != '') {
            return $user;
        } else {
            redirect(U('Wap/Users/login'));
        }
    }

    public function isLogin() {
        $user = unserialize(cookie('MX_USER'));
        if (!empty($user) && $user['userId'] > 0 && $user['userPhone'] != '') {
            return $user;
        } else {
            $user = array('userId' => 0);
            return $user;
        }
    }

    /**
     * 获取经纬度
     */
    public function getLonLat($address) {
        $address = urlencode($address);
        $ch = curl_init();
        $url = 'http://apis.baidu.com/3023/geo/code?a=' . $address;
        $header = array(
            'apikey: b1e361ecc709fa77f0f40896bf18c3ca',
        );
        // 添加apikey到header
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行HTTP请求
        curl_setopt($ch, CURLOPT_URL, $url);
        $res = curl_exec($ch);
        $res = json_decode($res, TRUE);

        return $res;
    }

    public function checkAddGoodsAuth($userInfo, $type = '') {
        $m = D('Wap/goods');
        $rs = $m->checkAddGoodsAuth($userInfo, $type);
        if ($rs['shopId'] > 0) {
            return $rs['shopId'];
        } else {
            $this->restApi($rs['code'], $rs['info']);
        }
    }

    /**
     * 单个上传图片
     */
    public function uploadImg($key, $is_head = 0) {
        $dir = I('dir', 'uploads') ? I('dir', 'uploads') : 'uploads';
        $config = array(
            'maxSize' => 0, //上传的文件大小限制 (0-不做限制)
            'exts' => array('jpg', 'png', 'gif', 'jpeg'), //允许上传的文件后缀
            'rootPath' => './Upload/', //保存根路径
            'driver' => 'LOCAL', // 文件上传驱动
            'subName' => array('date', 'Y-m'),
            'savePath' => $dir . "/"
        );
        $upload = new \Think\Upload($config);
        $rs = $upload->upload($_FILES);
        $Filedata = key($_FILES);
        if ($is_head) {
            $width = 220;
            $height = 220;
        } else {
            $width = I('width', 180) ? I('width', 180) : 180;
            $height = I('height', 180) ? I('height', 180) : 180;
        }

        if (!$rs) {
            return $upload->getError();
        } else {
            $images = new \Think\Image();
            $images->open('./Upload/' . $rs[$Filedata]['savepath'] . $rs[$Filedata]['savename']);
            $newsavename = str_replace('.', '_thumb.', $rs[$Filedata]['savename']);
            $vv = $images->thumb(I('width', 180), I('height', 180))->save('./Upload/' . $rs[$Filedata]['savepath'] . $newsavename);
            $rs[$Filedata]['savepath'] = "Upload/" . $rs[$Filedata]['savepath'];
            $rs[$Filedata]['savethumbname'] = $newsavename;
            if ($is_head) {
                $rs['picPath'] = $rs[$key]['savepath'] . $rs[$key]['savethumbname'];
                $rs['picThumbPath'] = $rs[$key]['savepath'] . $rs[$key]['savethumbname'];
            } else {
                $rs['picPath'] = $rs[$key]['savepath'] . $rs[$key]['savename'];
                $rs['picThumbPath'] = $rs[$key]['savepath'] . $rs[$key]['savethumbname'];
            }

            unset($rs['pic']);
            return $rs;
        }
    }

    /**
     * 微信JS支付
     */
    public function wxJsApiPay($order) {
        ini_set('date.timezone', 'Asia/Shanghai');
        vendor('Wxpay.lib.JSConfig');
        vendor('Wxpay.lib.WxPay_Api');
        vendor('Wxpay.lib.WxPay_JsApiPay');

        //①、获取用户openid
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();

        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetAppid(APPID);
        $input->SetMch_id(MCHID);
        $input->SetNonce_str(md5(time()));
        $input->SetSign();
        $input->SetBody("玉都微店");
//        $input->SetAttach("test");
        $input->SetOut_trade_no($order['orderSN']);
        $input->SetSpbill_create_ip(get_client_ip());
        $input->SetTotal_fee($order['priceSum'] * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url(C('WEB_URL') . "/WxpayAPI/example/notify.php");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);

        $WxPayApi = new \WxPayApi;
        $order = $WxPayApi::unifiedOrder($input);

        //exit;
        $jsApiParameters = $tools->GetJsApiParameters($order);

        return $jsApiParameters;
    }

    /**
     * 获取所有节点商品的ID
     * @param type $goodsId
     */
    public function getNodeGoodsId($goodsId) {
        $isSource = M('goods')->where('godosId=' . $goodsId)->getField('isSource');
        if ($isSource == 1) {
            $idArr = M('goods_resale')->where('sourceId=' . $goodsId)->field('goodsId')->select();
            $node = $goodsId;
        } else {
            $sourceId = M('goods_resale')->where('sourceId=' . $goodsId)->getField('sourceId');
            $idArr = M('goods_resale')->where('sourceId=' . $sourceId)->field('goodsId')->select();
            $node = $sourceId;
        }

        foreach ($idArr as $v) {
            $node .= ',' . $v['goodsId'];
        }
        $node = trim($node, ',');

        return $node;
    }

}
